<template>
    <div>
        <span :class="[isShow === false ?'form-onlyRead':'']" @click="handleCode">
            <span v-if="isShow" style="cursor: pointer">发送验证码</span>
            <span v-else style="cursor: text">{{countNum}}秒后再次发送</span>
        </span>
    </div>
</template>

<script>
    import {appid} from "../../assets/captcha/index"
    import {send_sms} from "../../request/api";

    export default {
        name: "TencentCaptcha",
        props: {
            phone: {
                type: String
            },
            scene: {
                type: String
            },
        },
        data() {
            return {
                captcha1: null,
                appid: appid,
                isShow: true,
                countNum:60,
                intervalBtn: null,
                isSms:false
            }
        },
        methods: {
            handleCode() {
                console.log('phone', this.phone);
                let reg = /^1[23456789]\d{9}$/;
                if (reg.test(this.phone)) {
                    this.captcha1.show();

                } else {
                    this.$message({
                        type: 'error',
                        message: "请先填写手机号"
                    })
                }
            },
            callbackName(res) {
                let params = {phone: this.phone, captcha: res, scene: this.scene}
                send_sms(params).then(res => {
                    console.log(res)
                    this.isSms = true;
                    this.isShow = false;
                    // 重置倒计时状态
                    this.countNum = 60;
                    this.intervalBtn = setInterval(() => {
                        if (this.countNum <= 1) {
                            // 清除定时器
                            clearInterval(this.intervalBtn)
                            this.isShow = true;
                        };
                        // 倒计时
                        this.countNum--;
                    }, 1000);
                }).catch(err => {
                    console.log('catch', err);
                    this.isShow = true;
                    this.$message({
                        type: "error",
                        message: err.msg
                    })
                    return;
                })
            }
        },
        mounted() {
            this.captcha1 = new TencentCaptcha(this.appid, this.callbackName);
        }
    }
</script>

<style scoped>
    .form-onlyRead {
        pointer-events: none;
    }
</style>
